<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  <!-- 设置字符编码为 UTF-8 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章</title>
    <link rel="icon" href="/img/favicon.png" type="image/png">
    <script src="libs/axios.min.js"></script>
    <script src="libs/vue.global.js"></script>
    <script src="libs/index.full.js"></script>
    <script src="js/navbar.js"></script>
    <link rel="stylesheet" href="libs/index.css">
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/article_detail.css">
</head>
<body>
<div id="app" class="full_container">
    <div id="navbar" class="navbar"></div>
    <div class="app_container">
        <!-- 文章内容 -->
        <div class="article-title">
            {{ article?.title }}
        </div>
        <span class="author">{{ article?.author }}</span>
        <span class="time">{{ formatTime(article?.publishedAt) }}</span>

        <div class="article-content">
            {{ article?.content }}
        </div>

        <div class="article-footer">
            <div>
                <span>点赞数: {{ article?.likes }}</span>
            </div>
            <div>
                <button class="like-button" @click="likeArticle">点赞</button>
                <button class="like-button" @click="collect">收藏</button>
            </div>
        </div>
    </div>

</div>
<script>
    const {createApp} = Vue;

    const {ElMessage} = ElementPlus;

    createApp({
        data(){
            return{
                article: [], // 存储分页数据
                articleId: 0,
                userId: 0,
                permissionLevel:0,
            }
        },
        mounted() {
            // 获取 URL 参数
            const urlParams = new URLSearchParams(window.location.search);
            this.articleId = urlParams.get("id");
            this.userId = urlParams.get("userId"); // 获取 userId
            if ((this.articleId > 0) && (this.userId > 0)) {
                this.fetchArticles(this.articleId);
            }
            this.getCurrentUser();

        },
        methods: {
            formatTime(timestamp) {
                const now = new Date();
                const messageDate = new Date(timestamp);

                const year = messageDate.getFullYear();
                const month = String(messageDate.getMonth() + 1).padStart(2, '0');
                const day = String(messageDate.getDate()).padStart(2, '0');
                const hours = String(messageDate.getHours()).padStart(2, '0');
                const minutes = String(messageDate.getMinutes()).padStart(2, '0');
                const seconds = String(messageDate.getSeconds()).padStart(2, '0');

                // 计算时间差
                const diffTime = now - messageDate;
                const diffDays = Math.floor(diffTime / (1000 * 3600 * 24)); // 转换为天数

                if (diffDays === 0) {
                    // 如果在今天，返回时分秒
                    return `${hours}:${minutes}`;
                } else if (diffDays === 1) {
                    // 如果昨天，返回“昨天”
                    return `昨天 `;
                } else {
                    // 如果超过昨天，返回日期 (MM/DD/YY)
                    return `${String(year).slice(2)}/${month}/${day}`;
                }
            },
            fetchArticles(id) {
                debugger
                axios.get(`http://localhost:8080/article/${id}`)
                    .then(response => {
                        this.article = response.data.data; // 获取文章详情
                    })
                    .catch(error => {
                        console.error("获取文章失败:", error);
                    });
            },
            // **分页切换**
            handlePageChange(newPage) {
                this.currentPage = newPage;
            },
            getCurrentUser() {
                axios.get('http://localhost:8080/chat/currentUser')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.currentUser = response.data.data.nickname;
                            this.currentUserAvatar = response.data.data.avatar;
                            this.permissionLevel = response.data.data.permissionLevel;
                        } else {
                            console.warn("未登录，跳转到登录页");
                            window.location.href = "/login.html"; // 重定向到登录页
                        }
                    })
                    .catch(error => console.error("获取当前用户失败:", error));
            },
            likeArticle(){
                debugger
                if(this.permissionLevel >= 2){
                    axios.get(`http://localhost:8080/article/like`, {
                        params: { articleId: this.articleId, userId: this.userId }
                    })
                        .then(response => {
                            ElMessage.success(response.data);
                            this.fetchArticles(this.articleId);
                        })
                        .catch(error => {
                            console.error("获取文章失败:", error);
                        });
                }else {
                    ElMessage.warning("对不起,您没有权限")
                }
            },
            collect(){
                if(this.permissionLevel >= 2){
                    const createTime = new Date().toISOString();
                    const data = {
                        userId: this.userId,
                        targetId: this.articleId,
                        targetType: 'article',
                        createTime: createTime,
                        url: `/article_detail.html?id=${this.articleId}&userId=${this.userId}`
                    };
                    axios.post(`http://localhost:8080/favorites/`, data)
                        .then(response => {
                            ElMessage.success("收藏成功");  // 显示成功消息
                        })
                        .catch(error => {
                            console.error("收藏失败:", error);
                        });
                }else {
                    ElMessage.warning("对不起,您没有权限")
                }
            }
        }
    }).use(ElementPlus).mount('#app');
</script>
</body>
</html>